package com.hxl.olympic.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.customview.widget.ViewDragHelper;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.google.gson.Gson;
import com.hxl.olympic.InitData;
import com.hxl.olympic.R;
import com.hxl.olympic.adapter.MyFragmentPagerAdapter;
import com.hxl.olympic.fragment.HomeFragment;
import com.hxl.olympic.fragment.InfoFragment;
import com.hxl.olympic.fragment.IssueFragment;
import com.hxl.olympic.fragment.MyFragment;
import com.hxl.olympic.fragment.PocketFragment;
import com.hxl.olympic.pojo.User;
import com.xuexiang.xui.widget.dialog.DialogLoader;
import com.xuexiang.xui.widget.guidview.FocusShape;
import com.xuexiang.xui.widget.guidview.GuideCaseQueue;
import com.xuexiang.xui.widget.guidview.GuideCaseView;
import com.xuexiang.xui.widget.textview.badge.Badge;
import com.xuexiang.xui.widget.textview.badge.BadgeView;
import com.xuexiang.xui.widget.toast.XToast;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class MainActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.vp)
    ViewPager vp;
    @BindView(R.id.tv_home)
    TextView tvHome;
    @BindView(R.id.tv_pocket)
    TextView tvPocket;
    @BindView(R.id.tv_info)
    TextView tvInfo;
    @BindView(R.id.tv_my)
    TextView tvMy;
    @BindView(R.id.img_issue)
    ImageView imgIssue;
    @BindView(R.id.layout_side)
    LinearLayout layoutSide;
    @BindView(R.id.layout_drawer)
    DrawerLayout layoutDrawer;

    private List<Fragment> fragments = new ArrayList<>();
    private Fragment homeFragment, infoFragment, pocketFragment, myFragment;
    private FragmentPagerAdapter fragmentAdapter;
    private List<TextView> tvs = new ArrayList<>();
    private boolean animFlag = true;
    private Animation operatingAnim1, operatingAnim2;
    private Drawable home1, home2, info1, info2, pocket1, pocket2, my1, my2;
    private BadgeView badgeView;
    private Badge infoBadge;
    private String userInfo;


    @Override
    public void initialize() {
        boolean guideCaseFlag = sp.getBoolean("guideCaseFlag", false);
        if (!guideCaseFlag) {
            //引导队列
            showTextGuideView();
            editor.putBoolean("guideCaseFlag", true);
            editor.commit();
        }
        userInfo = sp.getString("userInfo", "");
        app.setUserInfo(new Gson().fromJson(userInfo, User.class));
    }

    @Override
    public void initView() {
        //加载发布按键的动画
        operatingAnim1 = AnimationUtils.loadAnimation(this, R.anim.anim_issue1);
        operatingAnim2 = AnimationUtils.loadAnimation(this, R.anim.anim_issue2);

        //加载更换图片
        home1 = getResources().getDrawable(R.mipmap.ic_home1);
        home2 = getResources().getDrawable(R.mipmap.ic_home2);
        info1 = getResources().getDrawable(R.mipmap.ic_info1);
        info2 = getResources().getDrawable(R.mipmap.ic_info2);
        pocket1 = getResources().getDrawable(R.mipmap.ic_pocket1);
        pocket2 = getResources().getDrawable(R.mipmap.ic_pocket2);
        my1 = getResources().getDrawable(R.mipmap.ic_my1);
        my2 = getResources().getDrawable(R.mipmap.ic_my2);

        homeFragment = new HomeFragment();
        pocketFragment = new PocketFragment();
        infoFragment = new InfoFragment();
        myFragment = new MyFragment();
    }

    @Override
    public void initData() {
        //信息未读小红点提示
        badgeView = new BadgeView(context);
        infoBadge = badgeView.bindTarget(tvInfo);
        infoBadge.setBadgeBackgroundColor(getResources().getColor(R.color.orangered));
        infoBadge.setOnDragStateChangedListener((dragState, badge, targetView) -> {
        });

        tvs.add(tvHome);
        tvs.add(tvPocket);
        tvs.add(tvInfo);
        tvs.add(tvMy);

        fragments.add(homeFragment);
        fragments.add(pocketFragment);
        fragments.add(infoFragment);
        fragments.add(myFragment);
        fragmentAdapter = new MyFragmentPagerAdapter(fragmentManager, context, fragments);
        vp.setAdapter(fragmentAdapter);
        change(0);

        InitData.initType((FragmentActivity) context, app);
        //设置可侧滑边距以及侧滑全屏
        setDrawerLeftEdgeSize(context, layoutDrawer, 0.1f);

    }

    @Override
    @OnClick({R.id.tv_home, R.id.tv_pocket, R.id.tv_info, R.id.tv_my, R.id.img_issue})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_issue:
                if (userInfo.equals("") || app.getUserInfo() == null) {
                    toLogin();
                    return;
                }
                if (animFlag) {
                    animFlag = false;
                    imgIssue.startAnimation(operatingAnim1);
                    new Timer().schedule(new TimerTask() {
                        @Override
                        public void run() {
                            fragmentManager.beginTransaction().replace(R.id.layout_main, new IssueFragment())
                                    .addToBackStack(null)
                                    .commit();
                        }
                    }, 360);
                } else {
                    animFlag = true;
                    imgIssue.startAnimation(operatingAnim2);
                }
                break;
            case R.id.tv_home:
                change(0);
                break;
            case R.id.tv_pocket:
                change(1);
                break;
            case R.id.tv_info:
                change(2);
                break;
            case R.id.tv_my:
                change(3);
                break;
        }
    }

    public void toLogin() {
        //确认对话框
        DialogLoader.getInstance().showConfirmDialog(context, "暂未登录,赶快去登录吧!", "是", (dialog1, which) -> {
            app.setUserInfo(null);
            context.finish();
            startActivity(new Intent(context, LoginActivity.class));
        }, "否");
    }

    @Override
    protected void onResume() {
        super.onResume();
        //判断是否处于顶栈
        isAnimFlag();
    }

    public void isAnimFlag() {
        //判断是否处于顶栈
        if (!animFlag) {
            animFlag = true;
            imgIssue.startAnimation(operatingAnim2);
        }
    }

    /*
     *点击按钮或切换完页面时所要做的处理
     * */
    private void change(int num) {
        if (num != 0) {
            if (userInfo.equals("") || app.getUserInfo() == null) {
                toLogin();
                return;
            }
        }
        for (TextView tv : tvs) {
            tv.setTextColor(getResources().getColor(R.color.darkgray));
        }
        vp.setCurrentItem(num);
        tvs.get(num).setTextColor(getResources().getColor(R.color.black));

        tvHome.setCompoundDrawablesWithIntrinsicBounds(null, home1, null, null);
        tvPocket.setCompoundDrawablesWithIntrinsicBounds(null, pocket1, null, null);
        tvInfo.setCompoundDrawablesWithIntrinsicBounds(null, info1, null, null);
        tvMy.setCompoundDrawablesWithIntrinsicBounds(null, my1, null, null);
        switch (num) {
            case 0:
                tvHome.setCompoundDrawablesWithIntrinsicBounds(null, home2, null, null);
                break;
            case 1:
                tvPocket.setCompoundDrawablesWithIntrinsicBounds(null, pocket2, null, null);
                break;
            case 2:
                tvInfo.setCompoundDrawablesWithIntrinsicBounds(null, info2, null, null);
                break;
            case 3:
                tvMy.setCompoundDrawablesWithIntrinsicBounds(null, my2, null, null);
                break;
        }

    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }


    private boolean exit = false;

    /*
     *主界面退出应用再按一次处理
     * */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (fragmentManager.getBackStackEntryCount() == 0) {
                if (layoutDrawer.isDrawerOpen(layoutSide)) {
                    layoutDrawer.closeDrawer(layoutSide);
                    return true;
                }
                if (exit) {
                    finish();
                } else {
                    exit = true;
                    XToast.normal(context, "再按一次离开叮当", Toast.LENGTH_SHORT).show();
                    new Timer().schedule(new TimerTask() {
                        @Override
                        public void run() {
                            exit = false;
                        }
                    }, 1500);
                    return true;
                }
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /*
     *利用反射设置DrawerLayout滑动边距,以及侧滑全屏
     * */
    private void setDrawerLeftEdgeSize(Activity activity, DrawerLayout drawerLayout, float displayWidthPercentage) {
        if (activity == null || drawerLayout == null) return;
        try {
            Field leftDraggerField = drawerLayout.getClass().getDeclaredField("mLeftDragger");
            leftDraggerField.setAccessible(true);
            ViewDragHelper leftDragger = (ViewDragHelper) leftDraggerField.get(drawerLayout);
            Field edgeSizeField = leftDragger.getClass().getDeclaredField("mEdgeSize");
            edgeSizeField.setAccessible(true);
            int edgeSize = edgeSizeField.getInt(leftDragger);
            DisplayMetrics dm = new DisplayMetrics();
            activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
            edgeSizeField.setInt(leftDragger, Math.max(edgeSize, (int) (dm.widthPixels * displayWidthPercentage)));
        } catch (Exception e) {
        }
        //侧滑全屏
//        DisplayMetrics metric = new DisplayMetrics();
//        getWindowManager().getDefaultDisplay().getMetrics(metric);
//        int width = metric.widthPixels;     // 屏幕宽度（像素）
////        int height = metric.heightPixels;   // 屏幕高度（像素）
//        ViewGroup.LayoutParams leftParams = layoutSide.getLayoutParams();
////        leftParams.height = height;
//        leftParams.width = width;
//
//        layoutSide.setLayoutParams(leftParams);
    }

    /*
     *判断侧滑状态,打开或关闭侧滑
     * */
    public void openSide() {
        if (layoutDrawer.isDrawerOpen(layoutSide)) {
            layoutDrawer.closeDrawer(layoutSide);
        } else {
            layoutDrawer.openDrawer(layoutSide);
        }
    }

    /**
     * 显示文字引导
     */
    private void showTextGuideView() {
        final GuideCaseView guideStep1 = new GuideCaseView.Builder(context)
                .title("这里是首页,您可使用便捷功能及浏览资讯哦")
                .focusOn(tvHome)
                .fitWindowsAuto()
                .focusShape(FocusShape.ROUNDED_RECTANGLE)
                .build();

        final GuideCaseView guideStep2 = new GuideCaseView.Builder(context)
                .title("这里是我的,您可查看个人信息及进行设置哦")
                .focusOn(tvMy)
                .fitWindowsAuto()
                .focusShape(FocusShape.ROUNDED_RECTANGLE)
                .build();

        final GuideCaseView guideStep3 = new GuideCaseView.Builder(context)
                .title("最后,快发表一个你的动态吧")
                .focusOn(imgIssue)
                .fitWindowsAuto()
                .build();

        new GuideCaseQueue()
                .add(guideStep1)
                .add(guideStep2)
                .add(guideStep3)
                .show();
    }

}
